package com.dican.portal.consultas;

import java.io.IOException;
import java.sql.Connection;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dican.portal.login.Conexao;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;

public class ImprimePedido extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ImprimePedido() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String pedidoId = request.getParameter("pedId");
		JasperReport jasperReport = null;
		ServletOutputStream servletOutputStream = response.getOutputStream();
		byte[] bytes = null;
		Connection conn=null;
		try{
			jasperReport = JasperCompileManager.compileReport(getServletConfig().getServletContext().getRealPath("/reports/"+request.getParameter("relatname")+".jrxml"));
			conn = Conexao.getConnection();
			HashMap<String,String> hm = new HashMap<String,String>();
			hm.put("DOCUMENT_ID", pedidoId);
			bytes = JasperRunManager.runReportToPdf(jasperReport,hm, conn);
			conn.close();
			conn=null;
			response.setContentType("application/pdf");
			response.setContentLength(bytes.length);
			servletOutputStream.write(bytes, 0, bytes.length);
			bytes = null;
			servletOutputStream.flush();
			servletOutputStream.close();
		}
		catch (JRException e)
		{
			e.printStackTrace();
		}catch(Exception ex) {
			ex.printStackTrace();
		}
	}

}
